<?php

namespace Package\RedisHelper\config;

class RedisConfig
{
    private $host;
    private $port;
    private $password;
    private $database;
    private $timeout;
    private $persistent;
    private $prefix;
    private $retryInterval;
    private $readTimeout;
    private $serializer;
    
    public function __construct(array $config = [])
    {
        $this->host = $config['host'] ?? '127.0.0.1';
        $this->port = $config['port'] ?? 6379;
        $this->password = $config['password'] ?? null;
        $this->database = $config['database'] ?? 0;
        $this->timeout = $config['timeout'] ?? 0.0;
        $this->persistent = $config['persistent'] ?? false;
        $this->prefix = $config['prefix'] ?? '';
        $this->retryInterval = $config['retry_interval'] ?? 0;
        $this->readTimeout = $config['read_timeout'] ?? 0.0;
        $this->serializer = $config['serializer'] ?? \Redis::SERIALIZER_PHP;
    }
    
    // 验证配置是否有效
    public function validate(): void
    {
        if (!filter_var($this->host, FILTER_VALIDATE_IP) &&
            !filter_var($this->host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
            throw new \InvalidArgumentException("Invalid Redis host: {$this->host}");
        }
        
        if ($this->port < 1 || $this->port > 65535) {
            throw new \InvalidArgumentException("Invalid Redis port: {$this->port}");
        }
        
        if ($this->database < 0 || $this->database > 15) {
            throw new \InvalidArgumentException("Invalid Redis database: {$this->database}");
        }
    }
    
    // Getters
    public function getHost(): string { return $this->host; }
    public function getPort(): int { return $this->port; }
    public function getPassword(): ?string { return $this->password; }
    public function getDatabase(): int { return $this->database; }
    public function getTimeout(): float { return $this->timeout; }
    public function isPersistent(): bool { return $this->persistent; }
    public function getPrefix(): string { return $this->prefix; }
    public function getRetryInterval(): int { return $this->retryInterval; }
    public function getReadTimeout(): float { return $this->readTimeout; }
    public function getSerializer(): int { return $this->serializer; }
    
    // 转换为数组
    public function toArray(): array
    {
        return [
            'host' => $this->host,
            'port' => $this->port,
            'password' => $this->password,
            'database' => $this->database,
            'timeout' => $this->timeout,
            'persistent' => $this->persistent,
            'prefix' => $this->prefix,
            'retry_interval' => $this->retryInterval,
            'read_timeout' => $this->readTimeout,
            'serializer' => $this->serializer,
        ];
    }
}